package com.zlsy.learning.leetcode.binarysearch;

/**
 * @author zhouliang
 * @date 2020/9/23 15:52
 */
public class BsearchDemo2 {

  public static void main(String[] args) {
    int[] a = new int[] {1, 3, 4, 5, 6, 8, 8, 8, 11, 18};
    int n = a.length;
    int value = 8;
    System.out.println(bsearch(a, n, value));
  }

  /** 查找第一个值等于给定值的元素 */
  public static int bsearch(int[] a, int n, int value) {
    int low = 0;
    int high = n - 1;
    while (low <= high) {
      int mid = low + ((high - low) >> 1);
      if (a[mid] > value) {
        high = mid - 1;
      } else if (a[mid] < value) {
        low = mid + 1;
      } else {
        if ((mid == 0) || (a[mid - 1] != value)) {
          return mid;
        } else {
          high = mid - 1;
        }
      }
    }
    return -1;
  }
}
